package com.gupaoedu.mybatis.gp.plugin;

import com.gupaoedu.mybatis.gp.config.MapperRegistory;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class Plugin implements InvocationHandler {
    private Object target;
    private Interceptor interceptor;
    private Object[] pluginArray;

    public Plugin(Object target, Interceptor interceptor, Object[] pluginArray) {
        this.target = target;
        this.interceptor = interceptor;
        this.pluginArray = pluginArray;
    }

    public static Object wrap(Object target, Interceptor interceptor) {
        String interceptorName = interceptor.getClass().getName();
        Object[] pluginArray = MapperRegistory.signatureMap.get(interceptorName);
        if (pluginArray[0] == target.getClass().getInterfaces()[0]) {
            return Proxy.newProxyInstance(target.getClass().getClassLoader(),
                    target.getClass().getInterfaces(), new Plugin(target, interceptor, pluginArray));
        }
        return target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if(pluginArray[1].equals(method.getName())) {
            return interceptor.interceptor(new Invocation(target, method, args));
        }
        return method.invoke(target, args);
    }
}
